import { defineStore } from 'pinia';
import axios from 'axios';

export const chatStore = defineStore('chat', {
  state: () => ({
    chatHistories: [],
    currentChatHistory: null,
    loading: false,
    error: null
  }),

  actions: {
    // 获取用户的聊天历史列表
    async getUserChatHistories() {
      this.loading = true;
      this.error = null;
      try {
        const response = await axios.get('/chat');
        this.chatHistories = response.data;
        return response.data;
      } catch (error) {
        this.error = error.response?.data?.message || '获取聊天历史失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 获取单个聊天历史详情
    async getChatHistoryById(id) {
      this.loading = true;
      this.error = null;
      try {
        const response = await axios.get(`/chat/${id}`);
        this.currentChatHistory = response.data;
        return response.data;
      } catch (error) {
        this.error = error.response?.data?.message || '获取聊天详情失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 创建新的聊天
    async createChat(characterId) {
      this.loading = true;
      this.error = null;
      try {
        const response = await axios.post('/chat', { characterId });
        await this.getUserChatHistories(); // 刷新聊天历史列表
        return response.data;
      } catch (error) {
        this.error = error.response?.data?.message || '创建聊天失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 发送消息
    async sendMessage(historyId, content) {
      this.loading = true;
      this.error = null;
      try {
        const response = await axios.post(`/chat/${historyId}/messages`, { content });
        // 更新当前聊天历史
        if (this.currentChatHistory && this.currentChatHistory.id === historyId) {
          this.currentChatHistory.messages = response.data.messages;
        }
        // 刷新聊天历史列表
        await this.getUserChatHistories();
        return response.data;
      } catch (error) {
        this.error = error.response?.data?.message || '发送消息失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 更新聊天标题
    async updateChatTitle(historyId, title) {
      this.loading = true;
      this.error = null;
      try {
        const response = await axios.put(`/chat/${historyId}/title`, { title });
        // 更新当前聊天历史
        if (this.currentChatHistory && this.currentChatHistory.id === historyId) {
          this.currentChatHistory.title = response.data.title;
        }
        // 刷新聊天历史列表
        await this.getUserChatHistories();
        return response.data;
      } catch (error) {
        this.error = error.response?.data?.message || '更新聊天标题失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 删除聊天历史
    async deleteChatHistory(historyId) {
      this.loading = true;
      this.error = null;
      try {
        const response = await axios.delete(`/chat/${historyId}`);
        // 如果删除的是当前聊天历史，清除当前聊天
        if (this.currentChatHistory && this.currentChatHistory.id === historyId) {
          this.currentChatHistory = null;
        }
        // 刷新聊天历史列表
        await this.getUserChatHistories();
        return response.data;
      } catch (error) {
        this.error = error.response?.data?.message || '删除聊天历史失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 清空聊天消息
    async clearChatMessages(historyId) {
      this.loading = true;
      this.error = null;
      try {
        const response = await axios.delete(`/chat/${historyId}/messages`);
        // 更新当前聊天历史
        if (this.currentChatHistory && this.currentChatHistory.id === historyId) {
          this.currentChatHistory.messages = [];
        }
        return response.data;
      } catch (error) {
        this.error = error.response?.data?.message || '清空聊天消息失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 清除错误信息
    clearError() {
      this.error = null;
    },

    // 清除当前聊天历史
    clearCurrentChatHistory() {
      this.currentChatHistory = null;
    }
  },

  getters: {
    // 获取最新的聊天历史
    latestChatHistory: (state) => {
      if (state.chatHistories.length === 0) return null;
      return state.chatHistories[0];
    }
  }
});